package com.hunantv.mglive.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.mqtt.MqttService;
import com.hunantv.mglive.mqtt.data.MqttResponseData;
import com.hunantv.mglive.mqtt.data.MqttTokenData;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 达 on 2015/12/8.
 */
public class MqttChatUtils implements MqttCallback, HttpUtils.callBack {
    private static MqttChatUtils INSTANCE;
    private String mFlag;
    private String mKey;
    private final Object mObj = new Object();
    private Context mContext;
    private MqttCallback mCallback;
    private MqttService mqttService;
    private MqttTokenData tokenData;
    private ServiceConnection conn;
    private HttpUtils mHttp;
    //是否为上次聊天室重新连接标志  true:重连  false:新连
    private boolean isReconnet = false;

    private MqttChatUtils(Context context) {
        mContext = context;
        mHttp = new HttpUtils(context, this);
    }

    public static MqttChatUtils getInstance() {
        if (null == INSTANCE) {
            INSTANCE = new MqttChatUtils(MaxApplication.getAppContext());
        }
        return INSTANCE;
    }

    public boolean isReconnet() {
        return isReconnet;
    }

    public void setIsReconnet(boolean isReconnet) {
        this.isReconnet = isReconnet;
    }

    /**
     * 启动Service
     */
    public void startMqttService(String flag, String key, MqttCallback callback) {
        startMqttService(flag, key, false);
        this.mCallback = callback;
    }

    /**
     * 启动Service
     */
    private void startMqttService(String flag, String key, boolean isReconnet) {
        setIsReconnet(isReconnet);
        this.mFlag = flag;
        this.mKey = key;
        if (mqttService == null) {
            conn = new ServiceConnection() {
                /**
                 * 获取服务对象时的操作
                 */
                public void onServiceConnected(ComponentName name, IBinder service) {
                    mqttService = ((MqttService.ServiceBinder) service).getService();
                    connectChatRoom();
                }

                /** 无法获取到服务对象时的操作 */
                public void onServiceDisconnected(ComponentName name) {
                    Log.i("JUNE", "onServiceDisconnected===========无法获取到服务对象时的操作");
                    mqttService = null;
                }
            };
            Intent intent = new Intent(mContext, MqttService.class);
            mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE);
        } else {
            connectChatRoom();
        }
    }

    /**
     * 停止Service
     */
    public void stopMQTTService() {
        if (null != mqttService) {
            synchronized (mObj) {
                tokenData = null;
                mCallback = null;
                mFlag = null;
                mKey = null;
            }
            mqttService.actionStop(mContext);
//            mContext.unbindService(conn);
//            mqttService = null;
        }
    }

    public boolean isConnection(){
        return tokenData != null && mCallback != null && mFlag != null && mKey != null;
    }

    /**
     * 连接聊天室服务器
     */
    public void connectChatRoom() {
        Log.i("JUNE", "MqttChatUtils connectChatRoom url=" + BuildConfig.CHAT_REG_PATH + "?uuid=" + "" + "&flag=" + mFlag + "&key=" + mKey);
        Map<String, String> param = new HashMap<>();
        param.put("uuid", "");
        param.put("flag", mFlag);
        param.put("key", mKey);
        get(BuildConfig.CHAT_REG_PATH, param);
    }


    public String getFlag() {
        return mFlag;
    }

    public String getKey() {
        return mKey;
    }

    public String getClientId() {
        return tokenData != null ? tokenData.getClientId() : null;
    }

    /**
     * 连接丢失回调
     */
    @Override
    public void connectionLost(Throwable arg0) {
        mqttService.connectionLost();
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) {
        try {
            String msg = new String(mqttMessage.getPayload());
            Log.i("JUNE", "收到推送信息如下" +
                    " Topic: " + topic +
                    " Message: " + msg +
                    " QoS: " + mqttMessage.getQos());
            if(!StringUtil.isNullorEmpty(msg) && msg.endsWith("}"))
            {
                MqttResponseData responseData = JSON.parseObject(msg, MqttResponseData.class);
                L.d("JUNE", "mCallback != null?" + (mCallback != null));
                if (mCallback != null) {
                    mCallback.arrivedMessage(responseData);
                }
            }
        } catch (Exception e) {
            L.e(MqttChatUtils.class.getSimpleName(), e);
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        L.d(MqttChatUtils.class.toString(), "推送回调函数deliveryComplete方法执行");
    }


    @Override
    public boolean get(String url, Map<String, String> param) {
        return mHttp.get(url, param);
    }

    @Override
    public boolean post(String url, Map<String, String> param) {
        return mHttp.post(url, param);
    }

    @Override
    public void onError(String url, Exception e) {
        e.printStackTrace();
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        if (url.contains(BuildConfig.CHAT_REG_PATH)) {
            synchronized (mObj) {
                if (tokenData != null) {
                    tokenData = JSON.parseObject(resultModel.getData(), MqttTokenData.class);
                    if (mqttService != null) {
                        mqttService.actionChangeConnect(mContext, this, tokenData);
                    }
                } else {
                    tokenData = JSON.parseObject(resultModel.getData(), MqttTokenData.class);
                    if (mqttService != null) {
                        mqttService.actionStart(mContext, this, tokenData);
                    }
                }
                return tokenData;
            }
        }
        return null;
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) {
        if (url.contains(BuildConfig.CHAT_REG_PATH)) {
            if (null != mCallback && !isReconnet()) {
                mCallback.connectionSuccess();
            }
        }
    }


    public interface MqttCallback {
        public void arrivedMessage(MqttResponseData data);

        public void connectionSuccess();
    }
}
